﻿using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;

namespace spec_unsafe
{
    class nogc
    {
        static int[] bufarray = new int[4096];
        public unsafe static int[] GetATempShortArray(int len)
        {
            if (IntPtr.Size == 4) //32bit system
            {
                fixed (int* ptr = bufarray)
                {
                    //数组往前退一个指针长度就是大小
                    int* ptrsize = ptr - 1;
                    ptrsize[0] = len;
                    return bufarray;
                }
            }
            else //64bit system
            {
                fixed (int* ptr = bufarray)
                {
                    //数组往前退一个指针长度就是大小
                    long* ptrsize = (long*)ptr - 1;
                    ptrsize[0] = len;
                    return bufarray;
                }
            }
        }
        static string bufstr = new string(' ', 256);
        public unsafe static string GetABufStr(int len)
        {
            fixed (char* ptr = bufstr)
            {
                //数组往前退一个指针长度就是大小
                int* ptrsize = (int*)ptr - 1;
                ptrsize[0] = len;
                return bufstr;
            }
        }

        public unsafe static int strlen(char* ptr)
        {
            for (var i = 0; ; i++)
            {
                if (ptr[i] == 0)
                {
                    return i;
                }
            }
        }
        public unsafe static void strcpy(char* dest, string src)
        {
            for (var i = 0; i < src.Length; i++)
            {
                dest[i] = src[i];
            }
            dest[src.Length] = '\0';
        }
        public unsafe static void strcat(char* dest, string add)
        {
            int pos = strlen(dest);
            for (var i = 0; i < add.Length; i++)
            {
                dest[pos + i] = add[i];
            }
            dest[pos + add.Length] = '\0';
        }

        public static unsafe string ToString(char* ptr)
        {
            var len = strlen(ptr);
            var str = GetABufStr(len);
            fixed (char* pstr = str)
            {
                for (var i = 0; i < len; i++)
                {
                    pstr[i] = ptr[i];
                }
            }
            return str;
        }
        public unsafe static void ZeroEndStr()
        {
            char* p = stackalloc char[256];
            strcpy(p, "hello");
            strcat(p, "123");
            var str = ToString(p);
            Console.WriteLine("nogc str = " + str + "len=" + str.Length);
        }
    }
}
